#pragma once

#include "index.hpp"
#include "util.hpp"
#include <algorithm>
#include <jsoncpp/json/json.h>

namespace ns_searcher
{
    struct InvertedElemPrint
    {
        uint64_t doc_id;
        int weight;
        std::vector<std::string> words;
        InvertedElemPrint() : doc_id(0), weight(0) {}
    };
    class Searcher
    {
    private:
        ns_index::Index *index;

    public:
        Searcher() {}
        ~Searcher() {}

    public:
        void InitSearcher(const std::string &input)
        {
            // 1. 获取或创建Index实例
            index = ns_index::Index::GetInstance();
            // 2. 根据路径初始化
            index->BuildIndex(input);
        }
        void Search(const std::string &query, std::string *json_string)
        {
            // 1.拆分query
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query, &words);
            // 2.根据拆分结果进行查找
            std::vector<InvertedElemPrint> inverted_list_all;
            std::unordered_map<uint64_t, InvertedElemPrint> tokens_map; // id映射倒排元素
            for (std::string word : words)                              // 遍历关键词数组
            {
                boost::to_lower(word); // 关键词统一小写

                ns_index::InvertedList *inverted_list = index->GetInvertedList(word); // 获取倒排索引
                if (nullptr == inverted_list)
                    continue;

                for (const auto &elem : *inverted_list) // 遍历倒排索引
                {
                    auto &item = tokens_map[elem.doc_id]; // 根据倒排索引找到倒排元素
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight;
                    item.words.push_back(elem.word); // 将关键词添加到倒排元素的关键词集合中
                }
            }
            for (const auto &item : tokens_map)
            {
                inverted_list_all.push_back(std::move(item.second)); //
            }
            // 3.合并搜索结果（相关性降序）
            std::sort(inverted_list_all.begin(), inverted_list_all.end(),
                      [](const InvertedElemPrint &e1, const InvertedElemPrint &e2)
                      {
                          return e1.weight > e2.weight;
                      });
            // 4.根据查找出来的结果，构建json串
            Json::Value root;
            for (auto &item : inverted_list_all)
            {
                ns_index::DocInfo *doc = index->GetForwardIndex(item.doc_id);
                if (nullptr == doc)
                {
                    continue;
                }
                Json::Value elem;
                elem["title"] = doc->title;
                elem["url"] = doc->url;

                root.append(elem);
            }

            Json::StreamWriterBuilder writer;
            writer["indentation"] = "\t"; // 可以设置不同的缩进符号，比如空格或制表符
            std::unique_ptr<Json::StreamWriter> jsonWriter(writer.newStreamWriter());
            std::ostringstream os;
            jsonWriter->write(root, &os);
            *json_string = os.str();
        }
        std::string GetDesc(const std::string &html_content, const std::string &word)
        {
            // 找到word在html_content中的首次出现，然后往前找50字节(如果没有，从begin开始)，往后找100字节(如果没有，到end就可以的)
            // 截取出这部分内容
            const int prev_step = 50;
            const int next_step = 100;
            // 1. 找到首次出现
            auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), [](int x, int y)
                                    { return (std::tolower(x) == std::tolower(y)); });
            if (iter == html_content.end())
            {
                return "None1";
            }
            int pos = std::distance(html_content.begin(), iter);

            // 2. 获取start，end
            int start = 0;
            int end = html_content.size() - 1;
            // 如果之前有50+字符，就更新开始位置
            start = pos > start + prev_step ? pos - prev_step : start;
            end = pos < end - next_step ? pos + next_step : end;

            // 3. 截取子串,return
            if (start >= end)
                return "None2";
            std::string desc = html_content.substr(start, end - start);
            desc += "...";
            return desc;
        }
    };

};
